<script setup>
import { createDevice } from "@/api/device";
import { reactive, ref } from "vue";
import "@material/web/textfield/outlined-text-field.js";
import "@material/web/button/text-button";
import Dialog from "@/components/MaterialDialog.vue";

const props = defineProps(["open"]);
const emit = defineEmits(["open", "close", "done", "error"]);

const addDeviceForm = ref(null);

const formData = reactive({
  name: ""
});

async function onSubmit() {
  if (!addDeviceForm.value.reportValidity()) {
    return;
  }
  emit("close");
  try {
    const device = await createDevice(formData);
    addDeviceForm.value.reset();
    emit("done", device);
  } catch (ex) {
    emit("error", ex.toString());
  }
}

function onReset() {
  formData.name = "";
}
</script>

<template>
  <Dialog :open="open" @close="$emit('close')">
    <template #headline>
      创建设备
    </template>

    <template #content>
      <form id="add-device-form" ref="addDeviceForm" @submit.prevent="onSubmit" @reset="onReset">
        <p>
          <md-outlined-text-field label="设备名" type="name" required
            @keypress.enter.prevent="() => { $refs.addDeviceForm.requestSubmit() }" v-model="formData.name">
          </md-outlined-text-field>
        </p>
      </form>
    </template>

    <template #actions>
      <md-text-button type="reset" form="add-device-form">重置</md-text-button>
      <div style="flex: 1"></div>
      <md-text-button @click="$emit('close')">取消</md-text-button>
      <md-text-button type="submit" form="add-device-form">创建</md-text-button>
    </template>
  </Dialog>
</template>

<style scoped>
#add-device-form>p {
  margin-bottom: 16px;
}

#add-device-form>p:last-child {
  margin-bottom: 0;
}
</style>